#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

from enum import Enum
from common.env_common import get_install_head_path


class RoachConstant:
    VERSION = "gbase -V"
    COORDINATOR_CLUSTER = "gcadmin showcluster c"
    DATA_CLUSTER = "gcadmin showcluster d"
    GCWARE_CLUSTER = "gcadmin showcluster g"
    GCADMIN_ALL = "gcadmin"
    GCADMIN_VC_NAME = "gcadmin showcluster vc"
    ALL_SERVICE_INFO = "gcluster_services all info"
    ALL_GCWARE_INFO = "gcware_services all info"
    ADDRESS_FAMILY_AF_INET = 2


class AllStepEnum(str, Enum):
    ALLOW_BACKUP_IN_LOCAL_NODE = "AllowBackupInLocalNode"
    SUPPORT_RESOURCE = "ListApplicationResource"
    QUERY_JOB_PERMISSION = "QueryJobPermission"
    CHECK_BACKUP_JOB_TYPE = "CheckBackupJobType"
    PRE_TASK = "BackupPrerequisite"
    BACKUP = "Backup"
    QUERY_SCAN_REPOSITORIES = "QueryScanRepositories"
    POST_TASK = "BackupPostJob"
    STOP_TASK = "AbortJob"
    QUERY_BACKUP_COPY = "QueryBackupCopy"
    GENERATOR_SUB_JOB = "GeneratorSubJob"
    CHECK_APPLICATION = "CheckApplication"
    QUERY_CLUSTER = "QueryCluster"
    RESTORE_PREREQUISITE = "RestorePrerequisite"
    ALLOW_RESTORE = "AllowRestoreInLocalNode"
    RESTORE = "Restore"
    RESTORE_POST = "RestorePostJob"
    DELETECOPY = "DelCopy"
    CHECK_COPY = "CheckCopy"
    DELIVE_TASK_STATUS = "DeliverTaskStatus"
    RESTORE_GEN_SUB = "RestoreGenSubJob"
    BACKUP_GEN_SUB = "BackupGenSubJob"


class Env:
    USER_NAME = "application_auth_authKey"


class OsKeyword:
    USER_NAME = "os_username"
    USER_PASSWORD = "os_password"


class Status:
    ONLINE = "ONLINE"
    OFFLINE = "OFFLINE"


class ExitCode:
    SUCCESS = 0
    ERROR = 1


class RegisterType(int, Enum):
    ERR_TYPE = 0
    INSTANCE = 1
    DATABASE = 2


class ErrorCode(int, Enum):
    ERROR_INCREMENT_TO_FULL = 1577209901
    ERROR_DIFFERENT_VERSION = 1577209971
    ERROR_DIFFERENT_GBASE_TOPO = 1577213510
    ERROR_DIFFERENT_USER = 1577209973
    ERROR_MOUNT_PATH = 1577209974
    ERR_DATABASE_STATUS = 1577210000
    ERROR_USER_NOT_EXIST_CLUSTER = 0x5E0250D7
    ERR_RESTORED = 1577210101
    # 不支持修改数据库名称
    ERROR_RENAME_DATABASE_NAME = 1577209901
    # 某个服务未正常开启，返回参数 服务名称
    ERROR_SERVICE_1577213479 = 1577213479
    # 数据库不存在，返回参数 数据库名称
    ERROR_DB_NOT_EXIST = 1577213477
    # 数据库中存在非express引擎的表
    ERROR_DB_EXPRESS = 1677931783
    # 认证信息错误
    ERROR_AUTH = 1577209942
    # 参数错误
    ERROR_PARAM = 1677929218
    SYSTEM_ID_NOT_EXIST = 0
    DB_NODES_NOT_FULL_MATCH = 1677931026
    DB_ENV_ERROR = 2
    ACCESS_DB_ERROR = 3
    TENANT_MODEL_NOT_SUPPORT = 4
    DB_NOT_EXIST = 5
    # 集群不在线
    CLUSTER_NOT_ONLINE = 5
    # 不允许更换保护的数据库
    NOT_ALLOW_CHANGE_PROTECT_DB = 6
    # 不能修改数据库为新的数据库
    NOT_ALLOW_CHANGE_DB_TO_NEW_DB = 7
    # 不能修改数据库为新的数据库
    ERR_RENAME_DATABASE = 1577213482
    # 系统异常
    SYSTEM_ERROR = 1677929221
    # 不是所有数据库的服务都运行
    NOT_ALL_DB_SERVICE_RUNNING = 9
    # 增量转全量
    INC_TO_FULL = 0x5E02502D
    # 数据库不存在
    ERR_DB_NOT_EXIST = 1577210047
    # 指定节点上数据库不存在
    ERR_DB_NOT_EXIST_ON_NODE = 1577213536
    # 部署类型错误
    ERR_DEPLOY_TYPE = 0x5E02508B
    # 版本不支持
    ERR_NOT_SUPPORT_VERSION = 1677935120
    # 数据库环境异常不支持备份恢复
    ERR_ENVIRONMENT = 1577213475
    # 账号密码错误
    LOGIN_FAILED = 1677929488
    # 数据库服务异常
    ERR_DB_SERVICES = 1577213479
    # 输入参数错误
    ERR_INPUT_STRING = 1677934101
    # 主机选择有误
    ERR_CHOSEN_HOSTS = 1577209936
    # vc名称设置有误
    ERR_VC_NAME_WRONG = 1577209940

    ERR_USERNAME_OR_PASSWORD = 1577209938
    ERR_VC_NEEDED = 1577209941
    OPERATE_FAILED = 1677929219

    # 存在gcrcman运行进程 待基线
    PROCESS_EXISTED = 1577213508
    PATH_NOT_FOUND = 10
    ERROR_NO_GCRCMAN = 1577213509
    ERROR_NO_PEXPECT = 1577213507
    ERROR_DIFFERENT_DB = 1577213506
    # 原因：调用备份工具失败。 建议：请联系技术支持工程师协助解决
    BACKUP_TOOL_ERROR = 1577213505
    # 原因：Gbase执行恢复命令失败。
    # 建议：请收集日志并联系技术支持工程师协助解决。
    ERROR_EXECUTE_RESTORE_CMD = 1577212931
    # 原因：备份副本与恢复目标位置的数据库拓扑结构不一致。
    # 建议：请确保备份副本与恢复目标位置的数据库拓扑结构一致。
    ERROR_TOPOLOGY = 1577212932
    # 执行备份/恢复命令失败
    EXEC_BACKUP_RECOVER_CMD_FAIL = 1577209989


class EnvName:
    DB_USER_NAME = "application_auth_authKey"
    DB_PASSWORD = "application_auth_authPwd"
    CUSTOM_SETTINGS = "application_auth_extendInfo_authCustomParams"
    OS_USERNAME = "os_username"
    OS_PASSWORD = "os_password"
    CONCURRENCY_NUM = 4


class JsonConstant(str, Enum):
    STATUS = "status"
    VC_NAME = "vc_name"
    COPY_ID_LIST = 'copyIdList'
    AUTH_CUSTOM_PARAMS = "authCustomParams"
    APP_ENV = "appEnv"
    JOB_INFO = "jobInfo"
    JOB_PRIORITY = "jobPriority"
    JOB_TYPE = "jobType"
    HOSTS = "hosts"
    POLICY = "policy"
    SUB_JOB_ID = "subJobId"
    BASE_COPY_ID = "baseCopyId"
    CLUSTER_INFO = "cluster_info"
    CUSTOM_PARAMS = "customParams"
    DEPENDENCIES = "dependencies"
    CLUSTER_UUID = "clusterUuid"
    ORIGIN_PROTECT_ENV = "originProtectEnv"
    ORIGIN_PROTECTED_ENV = "originProtectedEnv"
    PROTECT_DATABASE = "database"
    SYSTEM_DB_USER = "systemDbUser"
    SYSTEM_DB_PASSWORD = "systemDbPassword"
    SYSTEM_ID = "systemId"
    SYSTEM_DB_PORT = "systemDbPort"
    EXTEND_INFO = "extendInfo"
    CLUSTER_TYPE = "clusterType"
    JOB = "job"
    JOB_PARAM = "jobParam"
    BACKUP_TYPE = "backupType"
    PROTECT_OBJECT = "protectObject"
    SUB_TYPE = "subType"
    PROTECT_ENV = "protectEnv"
    PROTECTED_ENV = "protectedEnv"
    ENDPOINT = "endpoint"
    AUTH = "auth"
    AUTH_KEY = "authKey"
    AUTH_PWD = "authPwd"
    INSTANCE_PORT = "instancePort"
    NODES = "nodes"
    REPOSITORIES = "repositories"
    REPOSITORY_TYPE = "repositoryType"
    PATH = "path"
    BACK_JOB_RESULT = "backupJobResult"
    COPY = "copy"
    COPY_ID = "copyId"
    TIMESTAMP = "timestamp"
    BACKUP_TIME = "backupTime"
    BACKUP_LIMIT = "BackupLimit"
    NAME = "name"
    COPIES = "copies"
    TARGET_OBJECT = "targetObject"
    RESTORE_JOB = "restoreType"
    RESTORE_JOB_RESULT = "restoreJobResult"
    PROGRESS = "progress"
    TASK_ID = "taskId"
    SUB_TASK_ID = "subTaskId"
    TASK_STATUS = "taskStatus"
    DATA_SIZE = "dataSize"
    SPEED = "speed"
    LOG_DETAIL = "logDetail"
    APPLICATION = "application"
    LIVE_MOUNT = "liveMount"
    TARGET_ENV = "targetEnv"
    ROLE = "role"
    ADVANCE_PARAMS = "advanceParams"
    SUB_JOB = "subJob"
    JOB_NAME = "jobName"
    RESTORE_TIMESTAMP = "restoreTimestamp"
    TYPE = "type"
    TYPES = "types"
    REMOTE_HOST = "remoteHost"
    REMOTE_PATH = "remotePath"
    MOUNT_JOB_ID = "mountJobId"
    LOG_INFO = "logInfo"
    LOG_INFO_PARAM = "logInfoParam"
    LOG_LEVEL = "logLevel"
    BACKUP_TASK_SLA = "backupTask_sla"
    POLICY_LIST = "policy_list"
    EXT_PARAMETERS = "ext_parameters"
    CHANNEL_NUMBER = "channel_number"
    NEW_DATABASE_NAME = "newDatabaseName"
    VERSION = "version"
    DATA_DIR = "dataDir"
    AVERAGE_SPEED = "averageSpeed"
    LOG_FLAG = "logFlag"
    LOG_FLAG_START_TIME = "logFlagStartTime"
    RESTORE_COPY_ID = "restoreCopyId"
    SERVICE_NAME = "serviceName"
    ID = "id"
    BACKUP_HOST_SN = "backupHostSN"
    FIRST_FULL_BACKUP_TIME = "firstFullBackupTime"
    NEXT_CAUSE_PARAM = "next_cause_param"
    HOST_AGENT = "hostAgent"
    BACKUP_ID = "backupId"
    SAPHANA_VERSION = "saphanaVersion"
    MULTI_TENANT_SYSTEM = "multiTenantSystem"
    IS_LOCAL = "isLocal"
    AGENT_IP_LIST = "agentIpList"
    JOB_ID = "jobId"
    FIRSTCLASSIFICATION = "firstClassification"
    POINT = "point"
    CYCLE = "cycle"
    HOSTSN_FILE_PATH = "/etc/HostSN/HostSN"
    IP_ADDRESS = "ip_address"
    DATA_NODE_NAME = "data_node_name"
    COORDINATOR_NAME = "coordinator_name"
    RELATED_HOST_IPS = "relatedHostIps"
    DEPLOY_TYPE = "deployType"


class GbaseTaskLabel(str, Enum):
    # "子任务（{0}）备份失败。"
    BACKUP_FAIL_LABEL = "plugin_backup_subjob_fail_label"
    # 执行前置任务失败
    PREREQUISITE_FAIL_LABEL = "plugin_execute_prerequisit_task_fail_label"
    # 生成子任务
    EXECUTE_GENERATE_SUBJOB_LABEL = "plugin_excute_generate_subjob_label"
    # "生成子任务失败。"
    GENERATE_SUBJOB_FAIL_LABEL = "plugin_generate_subjob_fail_label"
    # "生成子任务成功"
    GENERATE_SUBJOB_SUCCESS_LABEL = "plugin_generate_subjob_success_label"

    # "子任务（{0}）恢复失败。"
    RESTORE_SUBJOB_FAIL_LABEL = "plugin_restore_subjob_fail_label"
    # 子任务（{0}）执行成功。
    RESTORE_SUBJOB_SUCCESS_LABEL = "plugin_task_subjob_success_label"
    # "开始执行恢复子任务（{0}）。"
    RESTORE_START_COPY_SUBJOB = "plugin_start_restore_copy_subjob_label"
    # 开始执行恢复挂载子任务（{0}）。
    RESTORE_START_MOUNT_SUBJOB = "plugin_start_restore_prepare_subjob_label"


class NormalErr(int, Enum):
    NO_ERR = 0
    FALSE = -1
    WAITING = -2


class GbasePath:
    GBASE_FILESYSTEM_MOUNT_PATH = "/mnt/databackup/"
    GBASE_LINK_PATH = "/mnt/databackup/gbase"
    GCRCMAN_PATH = "server/bin/gcrcman.py"


DELETING_PATH_WHITE_LIST = [GbasePath.GBASE_FILESYSTEM_MOUNT_PATH, GbasePath.GBASE_LINK_PATH]


class CMDResult(str, Enum):
    SUCCESS = "0"
    FAILED = "1"


class CmdStr:
    DATABASE_BACKUP = "backup database {}{} level {}"
    LOGIN_GCRCMAN = "su - {} -c \"python {} -P -p -d {}\""
    LOGIN_SQL = "su - {} -c \"gbase -u {} -p \""
    SHOW_BACKUP = 'show backup'
    LN_CMD = 'ln -s {} {}'
    EXEC_RESULT_CODE = "echo $?"


class ProgressType:
    PRE = "pre"
    RESTORE_SUB = "backup_sub"
    POST = "post"


class GbaseBackupSubjobName:
    BACKUP = "backup"
    SUB_BACKUP = "sub_backup"
    MKDIR = "mkdir"
    LINK = "link"
    CONTACT_LINK = "contact_link"
    GENERABACKUP = "gen_backup"


class ProgressJob:
    progress_job_list = [
        AllStepEnum.PRE_TASK,
        AllStepEnum.BACKUP,
        AllStepEnum.POST_TASK,
    ]


class ResourceType:
    INSTANCE = '1'
    DATABASE = '2'


class BackupLevel:
    FULL = 0
    INCRE = 1


class RpcParamKey:
    APPLICATION = "application"
    TYPES = "types"
    FULL_COPY = "full"
    LOG_COPY = "log"
    INCREMENT_COPY = "increment"
    COPY_ID = "copyId"
    JOB_ID = "jobId"
    INPUT_FILE_PREFFIX = "rpcInput_"
    OUTPUT_FILE_PREFFIX = "rpcOutput_"
    QUERY_PREVIOUS_CPOY = "QueryPreviousCopy"
    REPORT_JOB_DETAILS = "ReportJobDetails"
    REPORT_COPY_INFO = 'ReportCopyAdditionalInfo'
    # 查询脚本
    RPC_TOOL = f"{get_install_head_path()}/DataBackup/ProtectClient/Plugins/GeneralDBPlugin/bin/rpctool.sh"
    # 输入参数文件目录
    PARAM_FILE_PATH = f"{get_install_head_path()}/DataBackup/ProtectClient/Plugins/GeneralDBPlugin/tmp"
    # 输出结果文件目录
    RESULT_PATH = f"{get_install_head_path()}/DataBackup/ProtectClient/Plugins/GeneralDBPlugin/stmp"


class LastCopyType:
    last_copy_type_dict = {
        2: [RpcParamKey.FULL_COPY, RpcParamKey.INCREMENT_COPY],
        3: [RpcParamKey.FULL_COPY],
    }


class SubJobPriority(int, Enum):
    JOB_PRIORITY_1 = 1,
    JOB_PRIORITY_2 = 2,
    JOB_PRIORITY_3 = 3,
    JOB_PRIORITY_4 = 4,


class SubJobType(int, Enum):
    PRE_SUB_JOB = 0,
    GENERATE_SUB_JOB = 1,
    BUSINESS_SUB_JOB = 2,
    POST_SUB_JOB = 3


class SubJobPolicy(int, Enum):
    LOCAL_NODE = 1,
    EVERY_NODE_ONE_TIME = 2,
    RETRY_OTHER_NODE_WHEN_FAILED = 3,
    FIXED_NODE = 4


class VCMode(int, Enum):
    SINGLE = 1
    MULTI = 2


class JobType(int, Enum):
    REGISTER = 1
    CHANGE = 2


class RestoreSubJobName(str, Enum):
    PREPARE_RESTORE = "prepare_restore"
    RESTORE = "restore"
    REFRESH = "refresh"


class GbaseEnvName:
    GCLUSTER_HOME = "GCLUSTER_HOME"
    GCLUSTER_BASE = "GCLUSTER_BASE"
    GCWARE_BASE = "GCWARE_BASE"
    GBASE_BASE = "GBASE_BASE"
    GBASE_HOME = "GBASE_HOME"


class PexpectResult:
    OS_LOGIN = ["password:", "password", "Password", "Password:", "密码", "密码：", "登录", "Last login", ]
    DB_LOGIN = ["password:", "password", "Password", "Password:", "口令", "口令：", "密码", "密码："]
    LOGIN_DATABASE_SUCCESS = ["gbase>"]


class LinkTaskType:
    BACKUP = "backup"
    RESTORE = 'restore'
    DELLINK = 'del_link'


class FileBackToolRET:
    SUCCESS = 1
    RUNNING = 2
    FAILED = 3


REPORT_INTERVAL_SEC = 30

SUPPORT_VERSION = "9.5"
